package com.twd.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.FileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.io.File;
import java.io.RandomAccessFile;

@ChannelHandler.Sharable
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    public static HttpRequestHandler INSTANCE = new HttpRequestHandler();
    private static File BASE_FILE;
    static {
        BASE_FILE = new File(HttpRequestHandler.class.getResource("/static").getFile());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        String uri = request.uri();
        if (uri.startsWith("/ws")) {
            // 升级为WebSocket协议
            ctx.fireChannelRead(request.retain());
            ctx.channel().writeAndFlush(new TextWebSocketFrame("s========================="));
        } else if (uri.startsWith("/static")) {
            // 文件传输
            HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), HttpResponseStatus.OK);
            String contentType = "text/html;charset=UTF-8";
            if (uri.endsWith(".js")) {
                contentType = "application/javascript; charset=utf-8";
            }
            response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);

            RandomAccessFile file = new RandomAccessFile(new File(BASE_FILE, uri.replace("/static/", "")), "r");
            FileRegion fileRegion = new DefaultFileRegion(file.getChannel(), 0, file.length());
            response.headers().add(HttpHeaderNames.CONTENT_LENGTH, file.length());
            ctx.write(response);
            ctx.write(fileRegion);
            ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            // 处理HTTP请求 ...
        }
    }
}
